////////////////////////////////////////////////////////////////////////////////
//
//  the linkury plugin event handlers 
//
////////////////////////////////////////////////////////////////////////////////

//When in production mode restore the following line to avoid console messages
//console.log = function () { };

// the linkury plugin
var minImgWidth = 100;
var minImgHeight = 100;
var floatingDistFromMouseY = -25;
var floatingDistFromMouseX = 15;
var smartbarHeight = LinkurySmartbarHeight;
var EventWrapper = "<?xml version='1.0' encoding='utf-8'?>\r\n<EventWrapper xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' Type='InputType' Xml='InputXml'/>"
var TextEventXml = '<?xml version="1.0" encoding="utf-8"?>\r\n<WebBrowserTextEventData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Guid="00000000-0000-0000-0000-000000000000" Text="InputText" Title="InputTitle" Url="InputUrl" />';
var ImageEventXml = '<?xml version="1.0" encoding="utf-8"?>\r\n<WebBrowserImageEventData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Guid="InputGuid" Source="InputSource" Title="InputTitle" Url="InputUrl" />';
var EmbedEventXml = '<?xml version="1.0" encoding="utf-8"?>\r\n<WebBrowserVideoEventData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Guid="InputGuid" Source="InputSource" Title="InputTitle" Url="InputUrl" />';

var port = chrome.extension.connect();

port.onMessage.addListener(function (msg) {
    if (msg.event == "IsSmartBarEnabled")
        CheckIfEnabledResponse(msg.response);
    if (msg.event == "CheckBlockedUrl")
        isBlockedResponse(msg.response);
    if (msg.event == "PopupElement")
        PopupElementResponse(msg.response);

    if (!blocked) {
        if (msg.event == "HideSmartBar") {
            popupDisabled = true;
        }

        if (msg.event == "ShowSmartBar") {
            popupDisabled = false;
        }

        if (msg.event == "RepositionElements") {
            if (msg.direction == "Down") {
                smartbarHeight = 0;
            }

            if (msg.direction == "Up") {
                smartbarHeight = LinkurySmartbarHeight;
            }

        }

        if (msg.event == "Refresh") {
            reloadPage();
        }
    }
});

chrome.extension.onConnect.addListener(function (port) {
    port.onMessage.addListener(function (msg) {

        if (msg.event == "IsSmartBarEnabled")
            CheckIfEnabledResponse(msg.response);
        if (msg.event == "CheckBlockedUrl")
            isBlockedResponse(msg.response);

        if (!blocked) {
            if (msg.event == "HideSmartBar") {
                popupDisabled = true;
            }

            if (msg.event == "ShowSmartBar") {
                popupDisabled = false;
            }

            if (msg.event == "RepositionElements") {
                if (msg.direction == "Down") {
                    smartbarHeight = 0;
                }

                if (msg.direction == "Up") {
                    smartbarHeight = LinkurySmartbarHeight;
                }

            }

            if (msg.event == "Refresh") {
                reloadPage();
            }
        }

    });
});


var blockHover = false;
console.log("Checking if in mapSiteList");
$.each(mapSiteList, function (value) {
    if (location.href.toLowerCase().indexOf(mapSiteList[value].toLowerCase()) != -1) {
        console.log("blockHover because in mapSiteList");
        blockHover = true;
    }
});

//$(document).ready(function() {
//    document.getElementsByTagName("body")[0].style.marginTop = '37px';
//    alert(document.getElementsByTagName("body")[0].style.marginTop);
//});
//var popupDiv = "<div name=\"popUpDiv\" ":





function RegisterEvents() {
    console.log("RegisterEvents()");

    //Removed frame events for babylon test version
    //TODO: remove comment for babylon production
    if (textSelectionEnabled) {
        $(document).mouseup(OnMouseUp);
        $(document).mousedown(OnMouseDown);
    }

    $(document).keydown(OnKeyDown);

	console.log("imagesHoverEnabled parameter is: " + imagesHoverEnabled);
	
    if (imagesHoverEnabled) {
		
		$(document).on('mouseout', 'img', function (e) {
            OnMouseOut(e, "OnMouseOut");
        });
		
		$(document).on('mouseover', 'img', function (e) {
            OnMouseOver(e, "OnMouseOver");
        });
		
		$(document).on('mouseover', '.stage', function (e) {
            OnMouseOver(e, "OnMouseOver");
        });
		
		$(document).on('mouseout', '.stage', function (e) {
            OnMouseOut(e, "OnMouseOut");
        });
    }

    if (videosHoverEnabled) {

		$(document).on('mouseout', 'embed', function (e) {
            OnMouseOut(e, "OnMouseOut");
        });
		
		$(document).on('mouseover', 'embed', function (e) {
            OnMouseOver(e, "OnMouseOver");
        });
    }

    if (searchBoxEnabled) {
        $(document).on('click', '#searchButton', function (e) {
            OnClick(e, "OnClick");
            // Live handler called.
        });
    }

    // setTimeout("javascript:RegisterFacebook()", 1000);
    //    document.addEventListener("mouseout", function(e) { OnMouseOut(e, "OnMouseOut"); }, true);
    //  document.addEventListener("mouseover", function(e) { OnMouseOver(e, "OnMouseOver"); }, true);
    //    setTimeout("javascript:RegisterEvents()", 2000);
}

function RegisterFacebook() {
    if ($(".spotlight").length > 0) {
        $(".spotlight").mouseout(OnMouseOut);
        $(".spotlight").mouseover(OnMouseOver);

        $(document).on('mouseout', ".spotlight", function (e) {
            OnMouseOut(e, "OnMouseOut");
        });

        $(document).on('mouseover', ".spotlight", function (e) {
            OnMouseOver(e, "OnMouseOver");
        });

        setTimeout("javascript:RegisterFacebook()", 1000);
        //  alert("spotlight");
    }

    else {
        setTimeout("javascript:RegisterFacebook()", 1000);
    }
    //    $("#fbPhotoTheater").live('mouseover', function (e) {

    //        OnMouseOver(e, "OnMouseOver");
    //        // Live handler called.
    //    });
}

function CheckIfEnabled() {
    port.postMessage({ event: "IsSmartBarEnabled" });
}

function CheckIfEnabledResponse(response) {
    try {
        console.log("documentEvents IsSmartBarEnabled:" + response.enabled + ", PopupEnabled:" + respone.popupDisabled);
        if (response.enabled) {
            if (response.direction == "Down") {
                smartbarHeight = 0;
            }

            if (response.direction == "Up") {
                smartbarHeight = LinkurySmartbarHeight;
            }
        }

        popupDisabled = response.popupDisabled
    }
    catch (e) {
        console.log("error:" + e);
    }
}

function RequestPopupElement() {
    port.postMessage({ event: "PopupElement" });
}


function PopupElementResponse(response) {
    if (response.html != null) {
        try {
            var htm = "<div name=\"popUpDiv\" id=\"popUpDiv\" isMouseOver=\"false\" class=\"popUpDivOff\" onmouseout=\"javascript:this.className='popUpDivOff';\" onmouseover=\"javascript:this.className='popUpDivOn';\" style=\"display:block;\">" + response.html + "</div>";
            $("body").append(htm);

            $("#popUpDiv img").each(function () {
                
                if ($(this).attr("id") == "searchButton" && searchBoxEnabled)
                    return;

                $(this).click(function () {
                    $("#popUpDiv").hide();
                    document.body.style.cursor = "wait";
                    setTimeout("javascript:document.body.style.cursor='auto'", 1500);
                    var tagName = currObj.tagName;
                    var hovedObjectTagName = tagName;
                    var hovedObjectHeight = currObj.height;
                    var hovedObjectWidth = currObj.width;
                    var pageTitle = currObj.ownerDocument.title;
                    var urlAddress = currObj.ownerDocument.URL;

                    if (tagName.toLowerCase() == "img") {
                        try {
                            var parsedEvent = ImageEventXml.replace("InputSource", escapeStringXml(currObj.src)).replace("InputUrl", escapeStringXml(urlAddress)).replace("InputTitle", escapeStringXml(pageTitle)).replace("InputGuid", $(this).attr("guid"));
                            var parsedEventWrapped = EventWrapper.replace("InputType", "WebBrowserImageEventData").replace("InputXml", escapeStringXml(parsedEvent));
                            port.postMessage({ event: "CallDataString", msg: parsedEventWrapped });

                            //   CallDataString(parsedEventWrapped);
                            // chrome.extension.sendRequest({ event: "ImgClicked", guid: $(this).attr("Guid"), url: urlAddress, title: pageTitle, source: currObj.src, tagName: hovedObjectTagName, height: hovedObjectHeight, width: hovedObjectWidth });

                        }
                        catch (e) {
                            console.log("error: " + e);
                        }
                    }
                    else if (tagName.toLowerCase() == "embed") {
                        try {
                            var objectUrl = currObj.style.backgroundImage;
                            if ((objectUrl == "") || typeof (objectUrl) == "undefined") {
                                objectUrl = urlAddress;
                            }

                            var parsedEvent = EmbedEventXml.replace("InputSource", escapeStringXml(objectUrl)).replace("InputUrl", escapeStringXml(urlAddress)).replace("InputTitle", escapeStringXml(pageTitle)).replace("InputGuid", $(this).attr("Guid"));
                            var parsedEventWrapped = EventWrapper.replace("InputType", "WebBrowserVideoEventData").replace("InputXml", escapeStringXml(parsedEvent));
                            port.postMessage({ event: "CallDataString", msg: parsedEventWrapped });

                        }
                        catch (e) {
                            console.log("error: " + e);
                        }
                    }


                });
            }
				);

            $("#popUpDiv").mouseleave(function () { HidePopup(); });
        }
        catch (e2) {
            console.log("error: " + e2);
        }
    }
}

function Run() {
    try {
        console.log("documentEvents main()");
        //   alert("Load: " + location.host);
        $("#popUpDiv").hide();
        CheckIfEnabled();


        RegisterEvents();
        //if(document.doctype != null)
        {
            // add the mouse event listeners

            //document.addEventListener("mouseup", function(e) { OnMouseUpDown(e, "OnMouseUp"); }, true);
            //document.addEventListener("mousedown", function(e) { OnMouseUpDown(e, "OnMouseDown"); }, true);

            var id = 1;


            //        $(":img[id]").each(function() {
            //            alert("test");
            //            id = id + 1;
            //            $(this).attr("id", "Linkury" + id);

            //        });

            //        $(":embed[id]").each(function() {

            //            id = id + 1;
            //            $(this).attr("id", "Linkury" + id);

            //        });
            //        $("img").wrap(function() {
            //            if ($(this).width() > minImgHeight && $(this).height() > minImgWidth) {
            //                id = id + 1;
            //                return '<div class="LinkuryBorderOff" id="Linkury' + id + '" name="Linkury' + id + '" onmouseout="javascript:this.className=\'LinkuryBorderOff\';" onmouseover="javascript:this.className=\'LinkuryBorderOn\';"/>';
            //            }
            //        });
        }
        // document.getElementsByTagName("body")[0].style.backgroundColor = "#AEAEB0 !important;";
        // window.addEventListener("load", evOnDocumentLoad, false);


        //    $("embed").wrap(function() {
        //        id = id + 1;
        //        return '<div class="LinkuryBorderOff" id="Linkury' + id + '" name="Linkury' + id + '" />';
        //    });
        console.log("Creating PopupElement");
        RequestPopupElement();
    }
    catch (e) {
        console.log("error: " + e);
    }
}



function HidePopup() {

    if (($("#popUpDiv").attr("isMouseOver") == "false") && !isOverImg) {

        $("#popUpDiv").hide();
    }
}


var popupDisabled = false;
function ShowPopup(object) {
    try {
        //  var cY = getY(object);
        // var cX = getX(object);
        //  if (!object.parentNode.id) {
        //     return;
        // }
        if (popupDisabled) {
            return;
        }
        var guiHeight = $("#popUpDiv").outerHeight();
        var top = $(object).offset().top;
        var cY = top - guiHeight - (localStorage["SmartbarEnabled"] ? smartbarHeight : 0);
        var cX = $(object).offset().left;
        var show = true;
        if ($("body").width() <= $("#popUpDiv").width() + cX) {
            show = false;
        }

        if ((window.top == window) && (top <= smartbarHeight)) {
            if ($("body").height() > $(object).outerHeight() + $("#popUpDiv").outerHeight()) {
                cY = $(object).offset().top + $(object).height() + smartbarHeight - guiHeight;
            }
            else {
                show = false;
            }
        }
        else if (window.top != window) {
            //we're not in the top frame, and the popup position is out of range
            if (cY < 0) {

                //Try to position below object
                if ($("body").height() > $(object).outerHeight() + $("#popUpDiv").outerHeight()) {
                    cY = $(object).offset().top + $(object).height() - guiHeight;
                }
                else {
                    show = false;
                }
            }
        }
        if (show) {
            $("#popUpDiv").css({ "top": cY, "left": (cX) });
            $("#popUpDiv").show();
        }
    }
    catch (e) {
        console.log("error: " + e);
    }

}





//$("div").each(function() {
//    if (($(this).css('background-image') != "none") && ($(this).css('background-image') != "")) {
//        id = id + 1;
//        $(this).wrap('<div class="LinkuryBorderOff" id="Linkury' + id + '" name="Linkury' + id + '" onmouseout="javascript:this.className=\'LinkuryBorderOff\';" onmouseover="javascript:this.className=\'LinkuryBorderOn\';"/>');
//    }
//});


//$("img").wrap('<div class="LinkuryBorderOff" onmouseout="javascript:this.className=\'LinkuryBorderOff\';HidePopup();" onmouseover="javascript:this.className=\'LinkuryBorderOn\';ShowPopup(this)"/>');
//$(chrome.extension.getBackgroundPage().getPopup()).appendTo("body");


function getY(oElement) {
    var iReturnValue = 0;
    while (oElement != null) {
        iReturnValue += oElement.offsetTop;
        oElement = oElement.offsetParent;
    }

    return iReturnValue;
}


function getX(oElement) {
    var iReturnValue = 0;
    while (oElement != null) {
        iReturnValue += oElement.offsetLeft;
        oElement = oElement.offsetParent;
    }
    return iReturnValue;
}

function escapeStringXml(s) {
    s = s.replace(/&/g, "&amp;");
    s = s.replace(/"/g, "&quot;");
    s = s.replace(/'/g, "&apos;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");

    return s;
}

function reloadPage() {
    try {
        console.log("reloadPage");
        window.location.reload();
    }

    catch (e) {
        console.log("error: " + e);
    }
}

// add the chrome event listener
chrome.extension.onRequest.addListener(
function (request, sender, sendResponse) {

    //  sendResponse({});
}
);


var selectedText = "";
var prevselectedText = "";
// mouse events handlers
function OnMouseUp(e) {
    console.log("OnMouseUp, popupDisabled - " + popupDisabled);
    if (popupDisabled) {

        return;
    }

    if (e.target.tagName.toLowerCase() == "input") {
        return;
    }

    if (e.target.tagName.toLowerCase() == "textarea") {
        return;
    }

    //This does not work for IE
    switch (e.which) {
        case 1:
            //Left button
            selectedText = window.getSelection().toString();
            break;
        case 2:
            //Middle button 

            break;
        case 3:
            //Right button

            break;

    }

    if (!searchBoxEnabled) {
        var pageTitle = "";
        try {
            pageTitle = e.target.parentNode.ownerDocument.title;
            //  alert(pageTitle);
        }
        catch (e) {
            console.log("error: " + e);
        }
        var urlAddress = "";
        try {
            urlAddress = e.target.parentNode.ownerDocument.URL;
        }
        catch (e) {
            console.log("error: " + e);
        }
        var parsedEvent = TextEventXml.replace("InputText", escapeStringXml(selectedText)).replace("InputUrl", escapeStringXml(urlAddress)).replace("InputTitle", escapeStringXml(pageTitle));
        var parsedEventWrapped = EventWrapper.replace("InputType", "WebBrowserTextEventData").replace("InputXml", escapeStringXml(parsedEvent));
        port.postMessage({ event: "CallDataString", msg: parsedEventWrapped });
    }
    else {
        $("#popUpDiv #searchDiv").hide();
        if (selectedText != "") {
            if (prevselectedText != selectedText) {
                prevselectedText = selectedText;
                $("#popUpDiv #popupMenuImage").hide();
                $("#popUpDiv #popupMenuVideo").hide();
                $("#popUpDiv #searchDiv").show();
                $("#popUpDiv").css({ "top": e.pageY - floatingDistFromMouseY, "left": e.pageX - floatingDistFromMouseX });
                $("#popUpDiv").show();
            } 
        }
    }
}

function OnClick(e) {
    chrome.extension.sendMessage({ event: "getFullUrl", url: searchBoxURL }, function (response) {
        url = response.url;
        var searchURL = url + "&q=" + encodeURIComponent(selectedText.substring(0, 300));
        window.open(searchURL);
    });
}

function OnKeyDown(e) {
    $("#popUpDiv").hide();
}


function OnMouseDown(e) {
    if (popupDisabled) {
        return;
    }
    if (searchBoxEnabled) {
        selectedText = "";
        return;
    }
    if ($("#popUpDiv").attr("isMouseOver") == "false") {
        var tagName = e.target.tagName;

        $("#popUpDiv").hide();
        if (tagName == "IMG") {
            $("#popUpDiv").hide();
        }
    }


    //   var selectedText = window.getSelection().toString();
    //  var pageTitle = e.target.parentNode.ownerDocument.title;
    //  var urlAddress = e.target.parentNode.ownerDocument.URL;
    //   chrome.extension.sendRequest({ event: "CallDataString", msg: parsedEventWrapped });
}



function OnMouseOut(e, eventType) {
    if (popupDisabled) {
        return;
    }
    if (searchBoxEnabled) {
        return;
    }
    var tagName = e.target.tagName;
    var hovedObjectTagName = tagName;
    var hovedObjectHeight = e.target.height;
    var hovedObjectWidth = e.target.width;
    var pageTitle = e.target.parentNode.ownerDocument.title;
    var urlAddress = e.target.parentNode.ownerDocument.URL;


    if (tagName == "IMG") {

        if (e.target.id != "LinkuryImages") {
            //   e.target.style.opacity = 1;

            isOverImg = false;
            setTimeout("javascript:HidePopup()", 100);
        }
        else {
            $("#popUpDiv").attr("isMouseOver", false);
        }

        //	e.target.className=" LinkuryBorderOff";
        //chrome.extension.sendRequest({ event: eventType, url: urlAddress, title: pageTitle ,source: e.target.src,tagName:hovedObjectTagName,height:hovedObjectHeight,width:hovedObjectWidth});
    }
    else {
        var className = e.target.className;
        if (className == "tagsWrapper") {
            //Patch for facebook theater mode!
            isOverImg = false;
            setTimeout("javascript:HidePopup()", 100);
        }
        else {
            isOverImg = false;
            setTimeout("javascript:HidePopup()", 100);
        }
    }
}

var isOverImg = false;
var currObj = null;
function OnMouseOver(e, eventType) {

    if (popupDisabled) {
        return;
    }
    if (blockHover) {
        return;
    }
    var tagName = e.target.tagName;

    if (tagName == "IMG") {


        if (e.target.id != "LinkuryImages") {
            if (e.target.height > minImgHeight && e.target.width > minImgWidth) {
                //  e.target.style.opacity = 0.8;
                isOverImg = true;
                currObj = e.target;
                $("#popUpDiv #searchDiv").hide();
                $("#popUpDiv #popupMenuImage").show();
                $("#popUpDiv #popupMenuVideo").hide();
                ShowPopup(e.target);
            }
        }
        else {
            $("#popUpDiv").attr("isMouseOver", true);
        }

    }

    else if (tagName == "EMBED") {
        isOverImg = true;
        currObj = e.target;
        $("#popUpDiv #searchDiv").hide();
        $("#popUpDiv #popupMenuImage").hide();
        $("#popUpDiv #popupMenuVideo").show();
        ShowPopup(e.target);
    }
    else {
        var className = e.target.className;
        if (className == "tagsWrapper") {
            var imgObj = $(e.target).parent().parent().children("img")[0];
            if (imgObj.height > minImgHeight && imgObj.width > minImgWidth) {
                //  e.target.style.opacity = 0.8;
                isOverImg = true;
                currObj = imgObj;
                $("#popUpDiv #searchDiv").hide();
                $("#popUpDiv #popupMenuImage").show();
                $("#popUpDiv #popupMenuVideo").hide();
                ShowPopup(imgObj);
            }
        }
    }

    //  else if (tagName == "DIV") {
    //        if (e.target.style.backgroundImage != "") {
    //            isOverImg = true;
    //            currObj = e.target;
    //            $("#popUpDiv #popupMenuImage").hide();
    //            $("#popUpDiv #popupMenuVideo").show();
    //            ShowPopup(e.target);
    //        }
    // }

}


///Entry Point
var blocked = false;
isBlocked();

function isBlockedResponse(response) {
    if (response.blocked != null) {
        blocked = JSON.parse(response.blocked) === true;
        console.log("isBlocked:" + blocked);
        //  alert(location.host + " state: " + response.blocked);
        if (!response.blocked) {
            try {
                Run();
            }
            catch (e) {
                console.log("error: " + e);
            }

        }
    }
}

function isBlocked() {
    try {
        console.log("checking isBlocked");
        port.postMessage({ event: "CheckBlockedUrl", url: location.href, host: location.host });

    }
    catch (e) {
        console.log("error: " + e);
        //alert(e);
    }
}


